package org.jprogger.myworld.api.response.handler;

import java.util.ArrayList;
import java.util.List;

import org.jprogger.myworld.api.ApiServiceInvocationException;
import org.jprogger.myworld.api.app.ApiParams;
import org.jprogger.myworld.api.model.Photo;
import org.jprogger.myworld.api.request.ApiRequest;
import org.jprogger.myworld.api.response.ApiResponse;
import org.jprogger.myworld.api.response.AbstractApiResponseHandler;
import org.jprogger.myworld.api.response.ApiResponseData;
import org.jprogger.myworld.api.response.ApiResponseError;
import org.jprogger.myworld.api.response.DefaultApiResponse;
import org.jprogger.myworld.api.response.DefaultApiResponseData;
import org.jprogger.myworld.api.response.ParseResponseException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class GetListPhotoApiResponseHandler extends AbstractApiResponseHandler<List<Photo>> {

	@Override
	public ApiResponse<List<Photo>> handleResponse(ApiRequest request, String response) throws ApiServiceInvocationException {
		
		ApiResponseError apiError = null;
		ApiResponseData<List<Photo>> apiData = null;
		ApiResponse<List<Photo>> apiResponse = new DefaultApiResponse<List<Photo>>();
		String format = request.getRequestFormat();
		try 
		{
			apiError = validateResponse(response, format);
			if (apiError == null)
			{
				if (format.equals(ApiParams.JSON_REQUEST_FORMAT))
				{
					apiData = new DefaultApiResponseData<List<Photo>>();
					List<Photo> photos = new ArrayList<Photo>();
					JSONArray jsonPhotos = new JSONArray(response);
					
					for (int i = 0; i < jsonPhotos.length(); i++) 
					{	
						Photo photo = new Photo();
						JSONObject jsonPhoto = jsonPhotos.getJSONObject(i);
						
						photo.setId(jsonPhoto.getString("pid"));
						photo.setAlbumId(jsonPhoto.getString("aid"));
						photo.setOwnerId(jsonPhoto.getString("owner"));
						photo.setPhotoUrl(jsonPhoto.getString("src"));
						photo.setThumbnailUrl(jsonPhoto.getString("src_small"));
						photo.setPhotoLargeUrl(jsonPhoto.getString("src_big"));
						photo.setCreationTime(jsonPhoto.getLong("created"));
						photo.setWidth(jsonPhoto.getInt("width"));
						photo.setHeight(jsonPhoto.getInt("height"));
						photo.setSize(jsonPhoto.getLong("size"));
						photo.setTitle(jsonPhoto.getString("title"));
						
						photos.add(photo);
					}
					
				}
				else if (format.equals(ApiParams.XML_REQUEST_FORMAT))  
				{
					// TODO: implement XML response format 
					throw new ApiServiceInvocationException("Unsupported response format");
				}
			}
			apiResponse.setError(apiError);
			apiResponse.setResponseData(apiData);
		} 
		catch (JSONException e) 
		{
			throw new ApiServiceInvocationException("Bad response format", e);
		}
		catch (ParseResponseException e) 
		{
			throw new ApiServiceInvocationException("Unable to parse response", e);
		}
		return apiResponse;
	}
}
